/**
 * <pre>
 * Title: 		CompositeIterator.java
 * Project: 	AnteAgent
 * Type:		com.hengpeng.util.scheduling.iterators.CompositeIterator
 * Author:		linriqing
 * Create:	 	2007-1-17 10:06:11
 * Copyright: 	Copyright (c) 2007
 * Company:		
 * <pre>
 */
package com.hengpeng.common.scheduling.iterators;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.tiling.scheduling.ScheduleIterator;

/**
 * <pre>
 * 多迭代器组合迭代器
 * </pre>
 * @author linriqing
 * @version 1.0, 2007-1-17
 */
public class CompositeIterator implements ScheduleIterator
{

	private List<Date> orderedTimes;

	private List<ScheduleIterator> orderedIterators;

	public CompositeIterator(ScheduleIterator ascheduleiterator[])
	{
		orderedTimes = new ArrayList<Date>();
		orderedIterators = new ArrayList<ScheduleIterator>();
		for (int i = 0; i < ascheduleiterator.length; i++)
		{
			insert(ascheduleiterator[i]);
		}

	}

	private void insert(ScheduleIterator scheduleiterator)
	{
		Date date = scheduleiterator.next();
		if (date == null)
		{
			return;
		}
		int i = Collections.binarySearch(orderedTimes, date);
		if (i < 0)
		{
			i = -i - 1;
		}
		orderedTimes.add(i, date);
		orderedIterators.add(i, scheduleiterator);
	}

	public synchronized Date next()
	{
		Date date;
		for (date = null; !orderedTimes.isEmpty() && (date == null || date.equals((Date) orderedTimes.get(0))); insert((ScheduleIterator) orderedIterators
				.remove(0)))
			date = (Date) orderedTimes.remove(0);

		return date;
	}
}
